package com.seata.demo.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.collections.CaseInsensitiveKeyMap;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;

/**
* @comments
* @author  zg
* @date 2021年2月16日
*/
@Slf4j
@Component
public class RequestHeaderInterceptor implements RequestInterceptor{

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String reqUri = null;
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            reqUri = request.getRequestURI();
            Enumeration<String> requestHeaderNames = request.getHeaderNames();
            if (requestHeaderNames != null) {
                Map<String, Collection<String>> resolvedHeaders = new CaseInsensitiveKeyMap<>();
                resolvedHeaders.putAll(template.headers());
                while (requestHeaderNames.hasMoreElements()) {
                    String requestHeaderName = requestHeaderNames.nextElement();
                    if (!resolvedHeaders.containsKey(requestHeaderName)) {
                        String requestValue = request.getHeader(requestHeaderName);
                        resolvedHeaders.put(requestHeaderName, Arrays.asList(requestValue));
                    }
                }
                template.headers(null);
                template.headers(resolvedHeaders);
            }
        }
        String xid = RootContext.getXID();
        if (StringUtils.isNotBlank(xid)) {
            template.header(RootContext.KEY_XID, xid);
        }
        log.info("RequestHeaderInterceptor......reqUri={}, xid={}", reqUri, xid);
    }
}
